﻿using Inovout.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
namespace Inovout.Web.Security
{
    public class WeiboOAuthClient : BaseOAuth2Client
    {
        private const string WeiboAuthorizationEndpoint = "https://api.weibo.com/oauth2/authorize?forcelogin=true";
        private const string WeiboTokenEndpoint = "https://api.weibo.com/oauth2/access_token";
        private const string WeiboUserDataServiceEndpoint = "https://api.weibo.com/2/users/show.json";

        public static readonly string OAuth2ClientProviderName = "weibo";
        public static readonly Dictionary<string, string> userDataMapping = new Dictionary<string, string>{
            {"id", "id"},{"username", "screen_name"},{"userloginimg", "profile_image_url"}
        };

        public WeiboOAuthClient(string providerName)
            : this(providerName, ComponentRegistry.Resolve<IApplication>().Settings["WeiboClientId"].ToString(),
                   ComponentRegistry.Resolve<IApplication>().Settings["WeiboClientSecret"].ToString(),
            userDataMapping,
            WeiboAuthorizationEndpoint,
            WeiboTokenEndpoint,
            WeiboUserDataServiceEndpoint
            )
        {
        }
        public WeiboOAuthClient()
            : this(OAuth2ClientProviderName,
                ComponentRegistry.Resolve<IApplication>().Settings["WeiboClientId"].ToString(),
                ComponentRegistry.Resolve<IApplication>().Settings["WeiboClientSecret"].ToString(),
            userDataMapping,
            WeiboAuthorizationEndpoint,
            WeiboTokenEndpoint,
            WeiboUserDataServiceEndpoint
                )
        {

        }

        public WeiboOAuthClient(string providerName, string clientId, string clientSecret,
                                    Dictionary<string, string> userDataMapping,
                                  string authorizeEndpoint, string tokenServiceEndpoint,
                                  string userDataServiceEndpoint,
                                   string scope = null)
            : base(providerName, clientId, clientSecret, userDataMapping, authorizeEndpoint, tokenServiceEndpoint,
            userDataServiceEndpoint,
            false, scope)
        {

        }

        protected override void AppendUserDataQuery(UriBuilder builder, AccessTokenInfo accessTokenInfo)
        {
            builder.AppendQueryArgument("uid", accessTokenInfo.ExtraData["uid"].ToString());
        }
    }
}
